﻿using System;
using System.IO;
using System.IO.Compression;
using System.Text;
using EPiServer.BaseLibrary.IO;

namespace TemplateFoundation.Tests.Environment
{
    [Serializable]
    public class AutoCompressString
    {
        // Fields
        private byte[] _compressedString;
        private static int _compressThreshold = 0;
        private string _originalString;
        private long _originalStringLength;
        public static readonly AutoCompressString Empty = new AutoCompressString(string.Empty);

        // Methods
        static AutoCompressString()
        {
            SetThreshold(1000);
        }

        private AutoCompressString()
            : this(null)
        {
        }

        public AutoCompressString(string str)
        {
            this._originalStringLength = -1L;
            if (((str != null) && (str.Length > 0)) && ((_compressThreshold > 0) && (str.Length > _compressThreshold)))
            {
                this._originalStringLength = this.Zip(str);
            }
            if (this._originalStringLength == -1L)
            {
                this._originalString = str;
            }
        }

        public static void SetThreshold(int val)
        {
            _compressThreshold = val;
        }

        public override string ToString()
        {
            if (this._compressedString != null)
            {
                return this.UnZip();
            }
            return this._originalString;
        }

        private string UnZip()
        {
            string str;
            MemoryStream stream = new MemoryStream(this._compressedString);
            using (Stream stream2 = new DeflateStream(stream, CompressionMode.Decompress))
            {
                using (MemoryStream stream3 = new MemoryStream())
                {
                    StreamConsumer.CopyToEnd(stream2, stream3);
                    str = Encoding.UTF8.GetString(stream3.GetBuffer(), 0, (int)stream3.Length);
                }
            }
            return str;
        }

        private long Zip(string str)
        {
            int byteCount = Encoding.UTF8.GetByteCount(str);
            using (MemoryStream stream = new MemoryStream())
            {
                using (Stream stream2 = new DeflateStream(stream, CompressionMode.Compress, true))
                {
                    stream2.Write(Encoding.UTF8.GetBytes(str), 0, byteCount);
                }
                this._compressedString = new byte[stream.Length];
                Buffer.BlockCopy(stream.GetBuffer(), 0, this._compressedString, 0, this._compressedString.Length);
            }
            if (this._compressedString.Length > byteCount)
            {
                this._compressedString = null;
                return -1L;
            }
            return (long)byteCount;
        }
    }


}
